package com.seari.gena.ciosClient.handler;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.Properties;

import com.seari.gena.ciosClient.CIOSSubscribeClient;
import com.seari.gena.task.CIOSupdateJob;
import com.seari.gena.task.QuartzManager;
import com.seari.utils.PropertiesUtil;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

public class CIOSSubscribeClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

	/**
	 * 向服务端发送数据
	 */
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("gena订阅通道-开启：" + ctx.channel().localAddress() + "channelActive");
		Properties prop = PropertiesUtil.loadConfig("gena.properties");
		InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIP = insocket.getAddress().getHostAddress();
		StringBuffer sb = new StringBuffer();
		sb.append("SUBSCRIBE " + "/Train" + " HTTP/1.1\r\n");
		sb.append("Host:" + clientIP+ "\r\n");
		sb.append("nt: gena:birth, gena:update, gena:death" + "\r\n");
		sb.append("Timeout:60000" + "\r\n");
//		sb.append("Call-Back:" + "http://172.26.200.23:52214" + "\r\n");
		sb.append("Call-Back:" + "http://"+prop.getProperty("CIOSClientIp1")+":"+ prop.getProperty("CIOSClientPort")+ "\r\n");
		sb.append("content-length:0" + "\r\n");
		sb.append("\r\n");
		System.out.println("gena订阅发送的数据包：" + sb.toString());
		ctx.writeAndFlush(Unpooled.copiedBuffer(sb.toString(), CharsetUtil.UTF_8));
	}

	/**
	 * 当客户端主动断开服务端的链接后，这个通道就是不活跃的。也就是说客户端与服务端的关闭了通信通道并且不可以传输数据
	 *
	 */
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("gena订阅通道-关闭：" + ctx.channel().localAddress() + "channelInactive");
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
		System.out.println("gena订阅channelRead");
		ByteBuf buf = msg.readBytes(msg.readableBytes());
		String retunMsg = buf.toString(Charset.forName("UTF-8"));
		System.out.println("订阅返回十六进制报文：" + ByteBufUtil.hexDump(buf));
		System.out.println("订阅返回报文：" + retunMsg);
		if(retunMsg.contains("200")) {
			System.out.println("订阅请求成功");
			String SID = retunMsg.split("\r\n")[3];
			System.out.println(SID);
//			QuartzManager qm = new QuartzManager();
//			qm.addJob(SID, "updateJob", SID, "updateTrigger", CIOSupdateJob.class, 20, SID);
		}else{
			System.out.println("主机订阅请求失败，开始备机订阅");
			Properties prop = PropertiesUtil.loadConfig("gena.properties");
			new CIOSSubscribeClient(prop.getProperty("ATSServerIp2"), Integer.parseInt(prop.getProperty("ATSServerPort"))).setup();
		};
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		ctx.close();
		System.out.println("订阅异常退出:" + cause.getMessage());
	}
}